<?php

namespace app\admin\controller\mycurrency\device;

use addons\mycurrency\library\Common;
use app\common\controller\Backend;
use app\common\library\device\cabinet\Analysis;
use think\exception\DbException;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 设备管理
 *
 * @icon fa fa-circle-o
 */
class Device extends Backend
{

    /**
     * Device模型对象
     * @var \app\admin\model\mycurrency\device\Device
     */
    protected $model = null;
    protected $noNeedRights = ['operate'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\mycurrency\device\Device;
        $this->view->assign("statusList", $this->model->getStatusList());
        $this->view->assign("useStatusList", $this->model->getUseStatusList());
        $this->view->assign("isFaultList", $this->model->getIsFaultList());
        $this->view->assign("isOnlineList", $this->model->getIsOnlineList());
        $this->view->assign("isInfraRedList", $this->model->getIsInfraRedList());
        $this->assignconfig('lattice', $this->auth->check('mycurrency/device/lattice/index')); //柜门列表权限
        $this->assignconfig('network', $this->auth->check('mycurrency/device/device/network')); //网络配置权限
        $this->assignconfig('preview', $this->auth->check('mycurrency/device/device/preview')); //柜子预览权限
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->with(['store'])
                    ->where($where)
                    ->order($sort, $order)
                    ->paginate($limit);

            foreach ($list as $row) {
                if($row['qrcode_image'] == null){
                    $content = config("mqtt.Host") . "device/{$row['number']}";//称重台二维码内容 
                    
                    $qrcode_image = Common::getCodewmImage($content,'device');
                    \app\common\model\mycurrency\Device::where(['id' => $row['id']])->update(['qrcode_image' => $qrcode_image]);
                    $row['qrcode_image'] = $qrcode_image;
                }
                $row->visible(['id','number','serial_number','status','use_status','is_fault','is_online','createtime','updatetime','qrcode_image','title','rssi','iccid','network','dev','is_infra_red']);
                $row->visible(['store']);
				$row->getRelation('store')->visible(['store_name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 配置网络
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function network($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        try {
            \app\common\model\mycurrency\Device::network(Analysis::CODE_CHAXUNWANGLUO,$ids,$params);
        } catch (ValidateException|PDOException|Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success();
    }

    /**
     * 柜子预览
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function preview($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        
        // 获取格口数据
        $latticeModel = new \app\admin\model\mycurrency\device\Lattice;
        $latticeList = $latticeModel->where('device_id', $ids)->where('deletetime', null)->order('number', 'asc')->select();
        
        $this->view->assign('row', $row);
        $this->view->assign('latticeList', $latticeList);
        return $this->view->fetch();
    }

    /**
     * 设备操作
     *
     * @return void
     * @throws \think\Exception
     */
    public function operate()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post();
            $code = intval($params['code']);
            $lattice_id = intval($params['lattice_id']);
            $pattern = $params['pattern'] ?? '';
            $delayed = intval($params['delayed'] ?? 0);
            
            try {
                $result = \app\common\model\mycurrency\Device::operateDevice(
                    $code,
                    $lattice_id,
                    [
                        'pattern' => $pattern,
                        'delayed' => $delayed
                    ]
                );

            } catch (ValidateException|PDOException|\Exception $e) {
                $this->error($e->getMessage());
            }
            $this->success('操作成功');
        }
        $this->error('非法请求');
    }

}
